<?php

namespace app\common\service;

use app\common\model\Message;
use app\common\model\UserDevice;
use think\facade\Cache;

class PushService
{
    public function getToken()
    {
        $file = __DIR__ . '/../tem/token.json';
        if (!file_exists($file)) {
            file_put_contents($file, '');
        }
        $data = json_decode(file_get_contents($file));
        if (empty($data) || $data->expire_time < $this->getMicroTime()) {
            $auth  = $this->auth();
            $token = $auth['token'];
            file_put_contents($file, json_encode($auth));
        } else {
            $token = $data->token;
        }
        return $token;
    }

    /**
     * 发送短信
     * @param string $code
     * @param array $param
     * @param string $mobile
     * @return bool
     */
    public function sms(string $mobile, string $code, array $param)
    {
        $list = Config::where('key', 'sms')->value('value');
        if (!$list) {
            return false;
        }
        $list = json_decode($list, true);

        $data = [];
        foreach ($list as $item) {
            $data[$item['key']] = $item;
        }
        if (!isset($data[$code])) {
            return false;
        }
        Alibaba::sendSms($mobile, $code, $param);
        return true;
    }

    /**
     * 推送
     * @return \push\Driver
     */
    public static function push()
    {
        $push = PushMessage::factory('getui', Config::getConf('push'));
        if (!Cache::store('redis')->has("token:getui")) {
            Cache::store('redis')->set('token:getui', $push->auth(), 86400);
        }
        $token = Cache::store('redis')->get("token:getui");
        $push->header($token);
        return $push;
    }

    /**
     * 发送消息
     * @param string|int $user_id
     * @param string $title
     * @param string $content
     * @param string $link
     * @return bool
     */
    public static function message($user_id, string $title, string $content, string $link = '/pages/user/message/message'): bool
    {
        $data['user_id'] = $user_id;
        $data['title']   = $title;
        $data['content'] = $content;
        $data['link']    = $link;
        $cid             = UserDevice::where('user_id', $user_id)->value('device_id');
        if ($cid) {
            $push = self::push();
            $push->setRequestId(uniqid());
            $push->setSettings();
            $push->setCid([$cid]);
            $push->setTitle($title);
            $push->setBody($content);
            $push->setClickType('payload', $link);
            $push->setPushMessage();
            $push->setPushChannel();
            $res = $push->single();

            if (!$res['code']) {
                $data['message_id']     = array_key_first($res['data']);
                $data['message_status'] = $res['data'][$data['message_id']][$cid];
            } else {
                $data['message_id']     = $res['code'];
                $data['message_status'] = $res['msg'];
            }
        }
        $push = self::create($data);
        $data['push_id'] = $push->id;
        $res = Message::create($data);
        if (!$res) {
            return false;
        }
        return true;
    }

    /**
     * 发送消息
     * @param array $cid
     * @param string $title
     * @param string $content
     * @param string $link
     * @return bool
     */
    public static function messageToList($user_id, array $cid, string $title, string $content, string $link = '/pages/user/message/message')
    {
        $message = new Message();
        $push = self::push();
        $array = array_chunk($cid, 1000, true);
        foreach ($array as $sub) {
            $cid = array_values(array_unique($sub));
            $push->setRequestId(uniqid());
            $push->setGroupName(date('YmdHis'));
            $push->setSettings();
            $push->setCid($cid);
            $push->setTitle($title);
            $push->setBody($content);
            $push->setClickType('payload', $link);
            $push->setPushMessage();
            $push->setPushChannel();
            $res = $push->list();

            $push = self::create([
                'user_id'        => $user_id,
                'title'          => $title,
                'content'        => $content,
                'link'           => $link,
            ]);

            if (!$res['code']) {
                $data = [];
                foreach ($sub as $k=>$v) {
                    $data[] = [
                        'user_id' => $k,
                        'title'          => $title,
                        'content'        => $content,
                        'link'           => $link,
                    ];
                }
                $message->saveAll($data);
            }
        }
        return true;
    }

    public static function messageToApp($tag, string $title, string $content, string $link = '/pages/user/message/message')
    {
        $push = self::push();
        $push->setRequestId(uniqid());
        $push->setSettings();
        $push->setGroupName(date('YmdHis'));
        $push->setAudience($tag);
        $push->setTitle($title);
        $push->setBody($content);
        $push->setClickType('payload', $link);
        $push->setPushMessage();
        $push->setPushChannel();
        $res = $push->app();
    }
}